package com.tanhua.dubbo.server.api;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.UserStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service(version = "1.0.0")
@Slf4j
public class UserStatusApiImpl implements UserStatusApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public UserStatus queryUserStatusById(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        return mongoTemplate.findOne(query,UserStatus.class);
    }

    @Override
    public Boolean saveUserStatus(UserStatus userStatus) {
        if (ObjectUtil.isAllEmpty(userStatus.getReasonsForFreezing(),userStatus.getUserId(),userStatus.getFreezingTime(),userStatus.getFreezingRange())){
            return false;
        }

        Query query = Query.query(Criteria.where("userId").is(userStatus.getUserId()));
        UserStatus one = mongoTemplate.findOne(query, UserStatus.class);
        if (!ObjectUtil.isEmpty(one)){
            return false;
        }

        mongoTemplate.save(userStatus);
        return true;
    }

    @Override
    public Boolean delUserStatus(Long userId) {
        try {
            Query query = Query.query(Criteria.where("userId").is(userId));
            UserStatus one = mongoTemplate.findOne(query, UserStatus.class);
            if (null == one){
                return null;
            }
            mongoTemplate.remove(one);
            return true;
        } catch (Exception e) {
            log.error("删除用户状态失败 userId= "+userId,e);
        }
        return false;
    }

    @Override
    public List<UserStatus> queryUserStatus(List<Long> userIds) {
        return null;
    }
}
